import React, { Component } from 'react'; // 这行必须写，不然报错，可能是eslint搞事情。
import { connect } from 'dva'; // connect用于组件连接models层数据
import {
  Row,
  Col,
  Input,
  Form,
  DatePicker,
  Space,
  Table,
  Button,
  Modal,
  Switch,
  message,
  TreeSelect,
  Select,
  Spin,
} from 'antd';
const { confirm } = Modal;
const { RangePicker } = DatePicker;
const { TreeNode } = TreeSelect;
const { Option } = Select;
import {
  SearchOutlined,
  PlusSquareOutlined,
  EditOutlined,
  DeleteOutlined,
  RedoOutlined,
  ExclamationCircleOutlined,
  ReloadOutlined,
  KeyOutlined,
} from '@ant-design/icons';

import { listRole, changeRoleStatus, delRole } from '@/api/system/role.js';
import AddroleModalForm from '@/components/role/addroleModalForm.js';
import EditroleModalForm from '@/components/role/editroleModalForm.js';
import EditRoleDeptModalForm from '@/components/role/editroledeptModalForm.js';
class SystemdeptPage extends Component {
  formRef = React.createRef();
  state = {
    // 查询参数e
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      roleName: undefined,
      roleKey: undefined,
      status: undefined,
    },
    // 总条数
    total: 0,
    // 日期范围
    dateRange: [],
    // 角色表格数据
    roleList: [],
    // 遮罩层
    loading: true,
    visible: false,
    editVisible: false,
    editRoleDeptVisible: false,
    roleid: null,
  };

  componentWillMount() {
    //查询角色列表
    this.getlist();
  }
  componentWillUnmount() {
    this.setState = () => false;
  }
  getlist = () => {
    //查询角色列表
    listRole(this.state.queryParams).then(res => {
      if (res.code == 200) {
        this.setState({
          roleList: res.rows,
          total: res.total,
          loading: false,
        });
      }
    });
  };

  //增加角色模态框
  showRoleModal = () => {
    this.setState({
      visible: true,
    });
  };

  //关闭角色模态框
  onhideRoleModal = () => {
    this.setState({
      visible: false,
    });
  };

  //修改角色
  editRoleModel = status => {
    this.setState({
      editVisible: true,
      roleid: status.roleId,
    });
  };

  //关闭 修改角色模态框
  onEditHideRoleModal = () => {
    this.setState({
      editVisible: false,
    });
  };

  //修改角色部门权限
  editRoleDeptModel = status => {
    this.setState({
      editRoleDeptVisible: true,
      roleid: status.roleId,
    });
  };
  onEditDeptHideRoleModal = () => {
    this.setState({
      editRoleDeptVisible: false,
    });
  };

  onFinish = values => {
    if (values.time !== undefined) {
      const rangeValue = values['time'];
      this.setState({
        queryParams: {
          ...this.state.queryParams,
          roleName: values.roleName,
          roleKey: values.roleKey,
          status: values.status,
          beginTime: rangeValue[0].format('YYYY-MM-DD'),
          endTime: rangeValue[1].format('YYYY-MM-DD'),
        },
      });
    } else {
      this.setState({
        queryParams: {
          ...this.state.queryParams,
          roleName: values.roleName,
          roleKey: values.roleKey,
          status: values.status,
        },
      });
    }
    this.getlist();
  };

  //重置
  Reload = () => {
    this.formRef.current.resetFields();

    this.setState({
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        roleName: undefined,
        roleKey: undefined,
        status: undefined,
        beginTime: undefined,
        endTime: undefined,
      },
    },()=>{
      this.getlist();
    });

  };

  render() {
    const that = this;

    const columns = [
      {
        title: '角色编号',
        dataIndex: 'roleId',
        key: 'roleId',
      },
      {
        title: '角色名称',
        dataIndex: 'roleName',
        key: 'roleName',
      },
      {
        title: '权限字符',
        dataIndex: 'roleKey',
        key: 'roleKey',
      },
      {
        title: '显示顺序',
        dataIndex: 'roleSort',
        key: 'roleKey',
      },
      {
        title: '状态',
        dataIndex: 'status',
        render: (status, record) => (
          <Switch
            defaultChecked={Number(status)}
            checked={Number(status)}
            onClick={nowStatus => {
              let textstate = nowStatus === true ? '启用' : '停用';
              confirm({
                title: `确认要${textstate}"${record.roleName}角色吗?"`,
                icon: <ExclamationCircleOutlined />,
                cancelText: '取消',
                okText: '确定',
                onOk() {
                  /** 更新用户状态 */
                  changeRoleStatus(record.roleId, `${Number(nowStatus)}`).then(
                    res => {
                      if (res.code == 500) {
                        message.warning(res.msg);
                        return false;
                      } else if (res.code == 200) {
                        message.success(textstate + '成功');
                        that.getlist()
                      }
                    },
                  );
                },
                onCancel() {
                  message.warning('取消成功');
                },
              });
            }}
          ></Switch>
        ),
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
      },
      {
        title: '操作',
        render: (status, record) => (
          <Space size="middle">
            <a onClick={() => this.editRoleModel(status)}>
              <EditOutlined />
              修改
            </a>
            <a onClick={() => this.editRoleDeptModel(status)}>
              <KeyOutlined />
              数据权限
            </a>
            <a
              onClick={() => {
                confirm({
                  title: `是否确认删除用户编号为${record.roleName}用户吗?"`,
                  icon: <ExclamationCircleOutlined />,
                  cancelText: '取消',
                  okText: '确定',
                  onOk() {
                    console.log();
                    delRole(record.roleId).then(res => {
                      if (res.code == 500) {
                        message.warning(res.msg);
                        return false;
                      } else if (res.code == 200) {
                        message.success(res.msg);
                        that.getlist();
                      }
                    });
                  },
                  onCancel() {
                    message.warning('取消成功');
                  },
                });
              }}
            >
              <DeleteOutlined />
              删除
            </a>
          </Space>
        ),
      },
    ];

    return (
      <>
        <Row gutter={24}>
          <Col xs={24}>
            <Form
              labelAlign="right"
              layout="horizontal"
              onFinish={this.onFinish}
              ref={this.formRef}
            >
              <Row>
                <Col className="userGrid">
                  <Form.Item label="角色名称" name="roleName">
                    <Input
                      style={{ width: '240px' }}
                      placeholder="请输入角色名称"
                    />
                  </Form.Item>
                  <Form.Item label="权限字符" name="roleKey">
                    <Input
                      style={{ width: '240px' }}
                      placeholder="请输入权限字符"
                    />
                  </Form.Item>
                  <Form.Item label="角色状态" name="status">
                    <Select style={{ width: '240px' }}>
                      <Option value={0}>停用</Option>
                      <Option value={1}>正常</Option>
                    </Select>
                  </Form.Item>
                  <Form.Item label="创建时间" name="time">
                    <RangePicker
                      style={{ width: '240px' }}
                      format="YYYY-MM-DD"
                    />
                  </Form.Item>
                </Col>
                <Col xs={24} xxl={20} span={20}>
                  <Form.Item>
                    <Button
                      type="primary"
                      icon={<SearchOutlined />}
                      htmlType="submit"
                      style={{ marginRight: '16px' }}
                    >
                      搜索
                    </Button>
                    <Button icon={<ReloadOutlined />} onClick={this.Reload}>
                      重置
                    </Button>
                  </Form.Item>
                </Col>
              </Row>
            </Form>
          </Col>
        </Row>

        <Row gutter={[16, 16]}>
          <Col span={1.5}>
            <Button
              type="primary"
              icon={<PlusSquareOutlined />}
              onClick={this.showRoleModal}
            >
              新增
            </Button>
          </Col>
          <Col span={1.5}>
            <Button danger="true" icon={<DeleteOutlined />}>
              删除
            </Button>
          </Col>
          <Col span={1.5}>
            <Button>导出</Button>
          </Col>
        </Row>

        <Spin spinning={this.state.loading}>
          {this.state.roleList.length && (
            <Table
              dataSource={this.state.roleList}
              columns={columns}
              rowKey={roleList => roleList.roleId}
            ></Table>
          )}
        </Spin>

        {/* 添加角色模态框 */}
        <AddroleModalForm
          visible={this.state.visible}
          onhideRoleModal={this.onhideRoleModal}
          onCancel={this.onhideRoleModal}
          oninitList={this.getlist}
        />

        {/* 修改角色模态框 */}
        {this.state.editVisible && (
          <EditroleModalForm
            visible={this.state.editVisible}
            onhideRoleModal={this.onEditHideRoleModal}
            onCancel={this.onEditHideRoleModal}
            oninitList={this.getlist}
            roleId={this.state.roleid}
          />
        )}
        {/* 修改角色权限模态框 */}
        {this.state.editRoleDeptVisible && (
          <EditRoleDeptModalForm
            visible={this.state.editRoleDeptVisible}
            roleId={this.state.roleid}
            onhideRoleModal={this.onEditDeptHideRoleModal}
            onCancel={this.onEditDeptHideRoleModal}
            oninitList={this.getlist}
          />
        )}
      </>
    );
  }
}

export default SystemdeptPage;
